import io

import pandas as pd
from pandas import DataFrame
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait


class BaseSpider:
    def __init__(self):
        ser = Service()
        ser.path = r"C:\Program Files\Google\Chrome\Application\chromedriver.exe"
        chrome_options = Options()
        chrome_options.binary_location = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
        chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
        driver = webdriver.Chrome(options=chrome_options, service=ser)
        driver.implicitly_wait(5)
        self.driver = driver
        print(f"初始化成功！")

    def parse_table_to_DataFrame(self, xpath) -> DataFrame:
        table = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.XPATH, xpath))
        )
        html = table.get_attribute('outerHTML')
        dfs: list[DataFrame] = pd.read_html(io.StringIO(html))
        for i in dfs:
            if not i.empty:
                return i
        return pd.DataFrame()

    def wait_and_click(self, selector):
        element = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, selector))
        )
        element.click()

    def wait_and_get_by_css(self, selector):
        element = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, selector))
        )
        return element

    def wait_and_get_by_xpath(self, xpath):
        element = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.XPATH, xpath))
        )
        return element

    def wait_and_gets_by_xpath(self, xpath):
        element = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_all_elements_located((By.XPATH, xpath))
        )

        return element

    def next_page(self) -> None:
        raise NotImplementedError

    def get_one_page(self) -> DataFrame:
        raise NotImplementedError

    def input_text(self, text):
        xpath = '//*[@id="goInput"]'
        # 完成翻页功能
        input_element = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.XPATH, xpath))
        )
        input_element.send_keys(text)


if __name__ == "__main__":
    BaseSpider()
